package com.bkfm.framework.core.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;

import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.springframework.web.context.ContextLoaderListener;

import com.bkfm.framework.core.utils.BkfmTableMetaDataCacheUtils;

/**
 * 
 *
 * @平台：统一开发平台
 * @文件名称：BkfmListener.java
 * @文件描述：
 * @author xuqiang
 * @日期：2018年7月19日上午8:52:20
 *
 */
public class BkfmListener extends ContextLoaderListener implements ServletContextListener,ServletRequestListener{

	private static final Logger logger = Logger.getLogger(BkfmListener.class);

	/**
	 * log4j日志追踪id
	 */
	public static final String LOG4J_ID_KEY = "EVENTID";
	
	/**
	 * log日期异常描述
	 */
	public static final String UNCAUGHT_EXCEPTION = "javax.servlet.error.exception";
	
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		super.contextInitialized(sce);
		try {
			BkfmTableMetaDataCacheUtils.initBkfmTableMetaDataCache();
		}catch(Exception e) {
			logger.error("执行缓存服务异常",e);
		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		super.contextDestroyed(sce);
		logger.error("系统注销");

	}

	@Override
	public void requestInitialized(ServletRequestEvent sre) {
		//添加日志追踪唯一编码
		MDC.put(LOG4J_ID_KEY, String.valueOf(System.currentTimeMillis()));
	}

	@Override
	public void requestDestroyed(ServletRequestEvent event) {
		Object object = event.getServletRequest().getAttribute(UNCAUGHT_EXCEPTION);
        if (object != null && object instanceof Throwable) {
            logger.error(UNCAUGHT_EXCEPTION, (Throwable) object);
        }
  		MDC.remove(LOG4J_ID_KEY);
	}
}
